package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    //前置处理
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头token
        String token = request.getHeader("Authorization");

        //2.当token不为空的时候,从redis中获取json数据
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        if (StrUtil.isNotBlank(token)) {
            String userJson = valueOperations.get(ConstantUtil.USER_TOKEN + token);
            //3.当json不为空的时候,转成user对象
            if (StrUtil.isNotBlank(userJson)) {
                User user = JSON.parseObject(userJson, User.class);
                //4.当user不为空的时候,将用户绑定到当前线程中,放行
                if (user != null) {
                    UserHolder.set(user);

                    //token的续期
                    valueOperations.set(ConstantUtil.USER_TOKEN+token,userJson, Duration.ofDays(30));
                    return true;
                }
            }
        }
        //5.以上任何一个不满足的时候,返回401
        response.setStatus(401);
        return false;
    }

    @Override
    //后置处理
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //解绑
        UserHolder.remove();
    }
}
